﻿#define DEBUG_AGENT
using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using System;
using System.Linq;
using System.Net;
using System.IO;
using System.Windows.Threading;
using System.Text.RegularExpressions;

namespace BackgroundAlarm
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        private static volatile bool _classInitialized;
        private string TASK_NAME = "BackgroundAlarm";

        /// <remarks>
        /// Le constructeur ScheduledAgent initialise le gestionnaire UnhandledException
        /// </remarks>
        public ScheduledAgent()
        {
            if (!_classInitialized)
            {
                _classInitialized = true;
                // S'abonner au gestionnaire d'exceptions prises en charge
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    Application.Current.UnhandledException += ScheduledAgent_UnhandledException;
                });
            }
        }

        /// Code à exécuter sur les exceptions non gérées
        private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // Une exception non gérée s'est produite ; arrêt dans le débogueur
                System.Diagnostics.Debugger.Break();
            }
        }

        /// <summary>
        /// Agent qui exécute une tâche planifiée
        /// </summary>
        /// <param name="task">
        /// La tâche appelée
        /// </param>
        /// <remarks>
        /// Cette méthode est appelée lorsqu'une tâche périodique ou  resource intensive est appelée
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {

           // if (task is PeriodicTask)
           // {
                GetVersion();
            //ChkVersion("2");
          //  }
           
        }
       
        private void ChkVersion(String version)
        {

            if (version != "1")
            {
                
                ShellToast myShellToast = new ShellToast();
                myShellToast.Title = "Tuzzit";
                myShellToast.Content = "New update available";
                myShellToast.Show();
            }

#if DEBUG_AGENT
            // If we're debugging, attempt to start the task immediately 
            ScheduledActionService.LaunchForTest(TASK_NAME, TimeSpan.FromSeconds(5));
#endif
            NotifyComplete();


        }

        private void GetVersion()
        {
            //HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://pierre42.dyndns-home.com:7890/tuzzit/version.php");
            //Test local 
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://192.168.1.20/tuzzit/version.php");
            request.CookieContainer = new CookieContainer();
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22";
            request.BeginGetResponse(new AsyncCallback(ReadWebNameCallback), request);
        }

        private void ReadWebNameCallback(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);
            using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
            {
                string results = httpwebStreamReader.ReadToEnd();
                // Dispatcher.BeginInvoke(() =>MessageBox.Show(results.ToString())); //-- on another thread!
                results = "@" + results;
                results = Regex.Replace(results, @"\n", "");
                results = Regex.Replace(results, @"\t", "");
                results = Regex.Replace(results, @".*<body>", "");
                results = Regex.Replace(results, @"</body>.*", "");
                results = Regex.Replace(results, "@", "");
                ChkVersion(results);
            }
            myResponse.Close();
           
            
        }

    }
}